package com.cucn.eduorder.service.impl;

import com.cucn.commonutils.ordervo.CourseWebVoOrder;
import com.cucn.commonutils.ordervo.UcenterMemberOrder;
import com.cucn.eduorder.client.EduClient;
import com.cucn.eduorder.client.UcenterClient;
import com.cucn.eduorder.entity.Order;
import com.cucn.eduorder.mapper.OrderMapper;
import com.cucn.eduorder.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.eduorder.utils.OrderNoUtil;
import com.cucn.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author KouChaoJie
 * @since 2021-10-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private EduClient eduClient;
    @Autowired
    private UcenterClient ucenterClient;

    /**
     * 生成订单的方法
     *
     * @param courseId 课程id
     * @param memberId 根据token值逆推的用户id
     * @return 订单号
     */
    @Override
    public String createOrders(String courseId, String memberId) {
        //通过远程调用根据用户id获取到用户信息
        UcenterMemberOrder userInfoOrder = null;
        try {
            userInfoOrder = ucenterClient.getUserInfoOrder(memberId);
        } catch (Exception e) {
            throw new GuliException(28004, "请先登录!");
        }

        //通过远程调用根据课程id获取课程信息
        CourseWebVoOrder courseInfoOrder = eduClient.getCourseInfoOrder(courseId);

        //将对应信息添加到数据库
        Order order = new Order();
        //订单号
        order.setOrderNo(OrderNoUtil.getOrderNo());
        //课程id
        order.setCourseId(courseId);
        //课程标题
        order.setCourseTitle(courseInfoOrder.getTitle());
        //课程封面
        order.setCourseCover(courseInfoOrder.getCover());
        //讲师名称
        order.setTeacherName(courseInfoOrder.getTeacherName());
        //课程价格
        order.setTotalFee(courseInfoOrder.getPrice());
        //用户id
        order.setMemberId(memberId);
        //用户手机号,昵称
        order.setMobile(userInfoOrder.getMobile());
        order.setNickname(userInfoOrder.getNickname());

        //支付状态 0.未支付1.已支付
        order.setStatus(0);
        //支付类型 1.微信2.支付宝
        order.setPayType(1);
        baseMapper.insert(order);

        //返回订单号
        return order.getOrderNo();
    }
}
